{[{  define "yuque/index.html" }]}
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>用户知识库</title>
    <link rel="stylesheet" href="/static/elementui/index.css"/>
    <link rel="stylesheet" href="/static/globalCss.css"/>

    <script src="/static/commonJS.js"></script>
</head>

<style>
    .el-table .category-row {
        --el-table-tr-bg-color: #a5a4a4;
    }
</style>

<body>

<div id="app">

    <el-input v-model="yqCookie" placeholder="请输入语雀的Cookie" type="textarea" max-rows="2"></el-input>
    <div style="float: right; margin: 10px">
        <el-button type="warning" @click="injectYqCookie">
            注入
        </el-button>
        <el-button type="primary" @click="getUserBooks">确认</el-button>
    </div>
    <el-table :data="allBooks"
              ref="booksTable"
              style="width: 100%; height: 80%; overflow-y: scroll"
              :show-1header="false"
              row-key="id"
              border
              @row-dblclick="dbClickBookRow"
              @select="selectBookRow"
              :row-class-name="computeRowClassName"
    >
        <el-table-column prop="name" label="name" min-width="25%">
        </el-table-column>
        <el-table-column prop="type" label="type" min-width="25%">
        </el-table-column>
        <el-table-column label="操作" min-width="20%">
            <template #default="scope">
                <el-button v-if="scope.row.type === 'book'" type="primary" @click="getDocs(scope.row)">下载</el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible"
               title="知识库列表"
               :z-index="1000"
               width="50%"
               style="height: 550px; overflow-y: scroll; min-width: 270px">
        <el-button type="primary" @click="downloadTocs" style="float: right; margin: 5px">下载</el-button>
        <el-table :data="docs"
                  ref="tocsTable"
                  style="width: 100%; height: 100%; overflow-y: scroll"
                  row-key="uuid"
                  border
                  :tree-props="{checkStrictly: true}"
                  @row-dblclick="dbClickTocRow"
                  @row-click="clickTocRow"
                  @select="selectTocRow"
        >
            <el-table-column type="selection" min-width="5%">
            </el-table-column>
            <el-table-column prop="title" label="title" min-width="25%">
            </el-table-column>
            <el-table-column prop="type" label="type" min-width="25%">
            </el-table-column>
        </el-table>
    </el-dialog>


    <el-dialog v-model="downloadDialogVisible"
               title="确认下载"
               :z-index="1000"
               width="50%"
               style="height: 550px; overflow-y: scroll; min-width: 270px">

        <p style="padding: 0 50px; margin-bottom: 10px;">
            <el-input v-model="categoryName" placeholder="请输入目录名称"></el-input>
            <span>是否覆盖文件: <el-switch v-model="coverOldFiles" /></span>
        </p>

        <p v-for="toc in selectedTocs" style="display: flex; padding: 5px 20px; text-align: left">
            <el-text class="mx-1"
                     type="primary"
                     size="large">
                [下载目录]\{{ categoryName }}\{{ toc.path }}
            </el-text>
        </p>

        <p>
            <el-button type="primary"
                       @click="confirmDownload"
                       style="margin: 20px;"
            >
                确认下载
            </el-button>
        </p>

    </el-dialog>

</div>

<script>
    bindApp("app", {
        data() {
            return {
                coverOldFiles: false,
                allBooks: [],
                yqCookie: "{[{.yqCookie}]}",
                selectedCategoryIdx: 0, // 选择的 Category 下标
                selectedBookIdx: 0, // 选择的 Book 下标
                dialogVisible: false,
                downloadDialogVisible: false,
                categoryName: "tmpCategory",
                selectedBook: {},
                docs: [],
                selectedTocs: [],
            }
        },
        mounted() {
            // this.getUserBooks();
        },
        methods: {
            dbClickBookRow(row) {
                // 点击知识库行
                if (row && row.children && row.children.length > 0) {
                    this.$nextTick(() => {
                        this.$refs.booksTable.toggleRowExpansion(row);
                    });
                }
            },
            clickTocRow(row) {
                if (row) {
                    this.$nextTick(() => {
                        this.$refs.tocsTable.toggleRowSelection(row);
                        // 触发 select 事件
                        const selectionRows = this.$refs.tocsTable.getSelectionRows();
                        if (selectionRows.length > 0) {
                            let needSelected = false;
                            selectionRows.forEach(selectedRow => {
                                if (selectedRow.uuid === row.uuid) {
                                    needSelected = true;
                                    return false;
                                }
                            });
                            if (needSelected) {
                                this.selectTocRow(selectionRows, row);
                            }
                        }
                    });
                }
            },
            dbClickTocRow(row) {
                if (row && row.children && row.children.length > 0) {
                    this.$nextTick(() => {
                        this.$refs.tocsTable.toggleRowExpansion(row);
                    });
                }
            },
            findCategory(row) {
                // 选择 Book 行时，找到所属的 Category 行
                if (row && row.type === "book") {
                    let selectedCategory = null;
                    // 记录 Category 的下标
                    let categoryIdx = 0;
                    let bookIdx = 0;

                    for (let category of this.allBooks) {
                        categoryIdx++;
                        bookIdx = 0;
                        for (let book of category.children) {
                            bookIdx++;
                            if (book.id === row.id) {
                                selectedCategory = category;
                                break;
                            }
                        }
                        if (selectedCategory) {
                            break;
                        }
                    }
                    if (selectedCategory) {
                        this.selectedCategoryIdx = categoryIdx;
                        this.selectedBookIdx = bookIdx;
                        this.categoryName = categoryIdx.toString().padStart(2, "0")
                            + "-" + selectedCategory.name;
                    }
                }
            },
            selectTocRow(selections, row) {
                if (row && row.parent_uuid) {
                    // 勾选行存在父级时，父级也进行勾选
                    this.$nextTick(() => {
                        const parentRow = this.docs.find(item => item.uuid === row.parent_uuid);
                        if (parentRow) {
                            this.$refs.tocsTable.toggleRowSelection(parentRow, true);
                            // 递归向上
                            this.selectTocRow(selections, parentRow);
                        }
                    });
                }
            },
            injectYqCookie() {

                const loading = startLoading();

                axios.get("/api/injectYqCookie", {
                    params: {
                        yqCookie: this.yqCookie
                    }
                }).then((data) => {
                    loading.close();
                    data = data.data;
                    if (data.code === 0) {
                        showMessage('success', data.message)
                    } else {
                        showMessage('error', data.message)
                    }

                }).catch((error) => {
                    loading.close();
                    showMessage('error', error.message)
                })
            },
            getUserBooks() {
                // 获取用户的所有知识库
                const loading = startLoading();

                axios.get("/api/getUserBooks", {
                    params: {}
                }).then((data) => {
                    loading.close();
                    data = data.data;
                    if (data.code === 0) {
                        this.allBooks = data.data;
                    } else {
                        this.$message({
                            message: data.message,
                            type: 'error'
                        })
                    }

                }).catch((error) => {
                    loading.close();
                    this.$message({
                        message: error.message,
                        type: 'error'
                    })
                })
            },
            computeRowClassName(row, rowIndex) {
                if (row && row.row && row.row.type === "category") {
                    return 'category-row'
                }
                return ''
            },
            getDocs(row) {
                this.dialogVisible = true;

                this.selectedBook = row;
                console.log("select row:", row);
                this.findCategory(row);
                var loading = startLoading();
                axios.get("/api/getDocs", {
                    params: {
                        loginUser: row.loginUser,
                        slug: row.slug,
                        bookIdx: this.selectedBookIdx
                    }
                }).then((data) => {
                    loading.close();
                    data = data.data;
                    if (data.code === 0) {
                        data.data.map((item) => {
                            item.tocTitle = item.title;
                        })
                        this.docs = data.data;
                    } else {
                        showMessage('error', data.message)
                    }

                }).catch((error) => {
                    loading.close();
                    showMessage('error', error.message)
                })
            },
            downloadTocs() {
                const selectedTocs = this.$refs.tocsTable.getSelectionRows();
                if (selectedTocs.length <= 0) {
                    showMessage('error', '请选择要下载的目录')
                    return;
                }
                // 对 selectedTocs 的 sequenceNo 字符串 进行排序
                selectedTocs.sort((a, b) => {
                    // 字符串排序
                    return a.sequenceNo.localeCompare(b.sequenceNo);
                });
                this.selectedTocs = selectedTocs;
                this.downloadDialogVisible = true;
            },
            confirmDownload() {

                if (this.selectedTocs.length <= 0) {
                    showMessage('error', '请选择要下载的目录')
                    return;
                }

                const loading = startLoading();
                axios.post("/api/downloadTocs", {
                    coverOldFiles: this.coverOldFiles,
                    categoryName: this.categoryName,
                    boodId: this.selectedBook.id,
                    bookIdx: this.selectedBookIdx + "",
                    bookName: this.selectedBook.name,
                    tocs: this.selectedTocs,
                    bookSlug: this.selectedBook.slug
                }).then((data) => {
                    loading.close();
                    data = data.data;
                    if (data.code === 0) {
                        // showMessage('success', data.message, 0)
                        confirmMsg(data.message, null, null, true);
                    } else {
                        // showMessage('error', data.message, 0)
                        confirmMsg(data.message, null, null, true);
                    }

                }).catch((error) => {
                    loading.close();
                    showMessage('error', error.message)
                })
            }
        }
    })
</script>

</body>
</html>
{[{ end }]}